package com.tjh.gulimall.order.interceptor;

import com.tjh.common.constant.AuthServerConstant;
import com.tjh.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create by koala on 2021-05-17
 */
@Component//加入容器中
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /**
         * day130：远程服务调用无需登录
         */
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/order/order/status/**", requestURI);
        boolean match1 = antPathMatcher.match("/payed/notify", requestURI);
        if (match || match1){
            return true;
        }

        /**
         * day116：拦截器，拦截未登录的服务
         *      作用：访问订单服务的任何一个请求，拦截未登录用户请求，跳转登录页
         *      测试：
         *          1、浏览器访问购物车页面：http://cart.gulimall.com/cart.html
         *          2、点击结算按钮去结算
         *          3、查看登录状态与未登录状态的不同跳转结果（未登录状态下跳转登录页，已登录状态下跳转结算页）
         */
        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            loginUser.set(attribute);
            return true;
        }else {
            //没登录
            request.getSession().setAttribute("msg","请先登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}